<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;

class Swiper extends Model
{
    use SoftDeletes;

    const DISPLAY_POSITION_INDEX = 1;

    public static $displayPositionText = [
        self::DISPLAY_POSITION_INDEX => '首页',
    ];

    const JUMP_TYPE_TOPIC = 1;
    const JUMP_TYPE_LINK = 2;

    public static $jumpTypeText = [
        self::JUMP_TYPE_TOPIC => '帖子',
        self::JUMP_TYPE_LINK => '链接',
    ];

    protected $fillable = ['display_position', 'description', 'image', 'begin_time', 'end_time', 'jump_type', 'jump_value', 'display_order'];

    public function getJumpTypeTextAttribute()
    {
        return self::$jumpTypeText[$this->jump_type] ?? '';
    }

    public function getDisplayPositionTextAttribute()
    {
        $results = [];
        foreach ($this->display_position as $value) {
            $results[] = self::$displayPositionText[$value] ?? '';
        }
        return implode('、', array_filter($results));
    }

    public function getDisplayPositionAttribute($value)
    {
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setDisplayPositionAttribute($value)
    {
        if (is_array($value)) {
            $this->attributes['display_position'] = implode(',', $value);
        }
    }

    public function scopeDisplayInIndex($query)
    {
        $query->whereRaw(sprintf("find_in_set('%s', display_position)", self::DISPLAY_POSITION_INDEX));
    }

    public function scopeOnlyValid($query)
    {
        $query->where('begin_time', '<=', Carbon::now())->where('end_time', '>=', Carbon::now());
    }

}
